import { useEffect, useState } from 'react';
import { Table, Button, message, Space, Typography, Layout } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { workflowService, WorkflowItem } from '../services/workflow.service';
import Workflow from './workflow';

const { Content } = Layout;
const { Title } = Typography;

export default function WorkFlowList({ onSelect }: { onSelect: (code: string) => void }) {
  const [workflows, setWorkflows] = useState<WorkflowItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [editingWorkflowId, setEditingWorkflowId] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState(false);

  const fetchWorkflows = async () => {
    try {
      setLoading(true);
      const data = await workflowService.fetchWorkflowList();
      if (data) {
        setWorkflows(data);
      }
    } catch (err: unknown) {
      console.error('请求异常:', err);
      message.error(err instanceof Error ? err.message : '获取异常');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWorkflows();
  }, []);

  const handleEdit = (id: string) => {
    setEditingWorkflowId(id);
  };

  const handleCreate = () => {
    setIsCreating(true);
  };

  const handleBack = () => {
    setEditingWorkflowId(null);
    setIsCreating(false);
    fetchWorkflows(); // 返回时刷新列表
  };

  const handleDelete = async (id: string) => {
    try {
      await workflowService.deleteWorkflow(id);
      message.success('删除成功');
      fetchWorkflows();
    } catch (err: unknown) {
      console.error('删除失败:', err);
      message.error(err instanceof Error ? err.message : '删除失败');
    }
  };

  const columns = [
    {
      title: '流程名称',
      dataIndex: 'workflow_name',
      key: 'workflow_name',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: 'ID',
      dataIndex: 'workflow_id',
      key: 'workflow_id',
      width: '300px',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: WorkflowItem) => (
        <Space>
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record.workflow_id)}>
            编辑
          </Button>
          <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.workflow_id)}>
            删除
          </Button>
        </Space>
      )
    }
  ];

  // 如果正在编辑或创建，显示工作流编辑器
  if (editingWorkflowId || isCreating) {
    return (
      <Layout className="site-layout">
        <Content style={{ margin: '0 16px', padding: 24, minHeight: 280 }}>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={handleBack}
            style={{ marginBottom: 16 }}
          >
            返回列表
          </Button>
          <Workflow 
            workflowId={editingWorkflowId} 
            onSaved={handleBack}
          />
        </Content>
      </Layout>
    );
  }

  // 否则显示列表
  return (
    <Layout className="site-layout">
      <Content style={{ margin: '0 16px', padding: 24, minHeight: 280 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Title level={2}>流程列表</Title>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleCreate}
          >
            新建流程
          </Button>
        </div>
        
        <Table
          columns={columns}
          dataSource={workflows}
          rowKey="workflow_id"
          loading={loading}
          bordered
        />
      </Content>
    </Layout>
  );
} 